const shellHelper = require('../libs/shellHelper')
const kits = require('../kits.json')
const inquirer = require('inquirer');
const chalk = require('chalk');
const path = require('path');
const fs = require('fs');
const ora = require('ora');
const spinner = ora();
const FsHelper = require('../libs/FsHelper');
const initSetting = require('../initSetting');

const sleep = (timeout) => new Promise((resolve, reject) => setTimeout(() => resolve(true), timeout))

const isWin = process.platform.startsWith('win')

const gitClone = async (url, directory, branch) => {
  if (branch) {
    return shellHelper.execa('git', ['clone', `${url}`, `-b`, `${branch}`, `${directory}`])
  }
  return shellHelper.execa('git', ['clone', `${url}`, `${directory}`])
}

const install = async (directory) => {
  let result = await shellHelper.execa(`yarn`, [`install`], { cwd: directory, })
  if (result.exitCode === 0) return result

  return shellHelper.execa(`npm`, [`install`], { cwd: directory, })
}

const clearGit = async (directory) => {
  // return isWin ? shellHelper.shell.rm(`-rf`, `${directory}/.git`) : shellHelper.execa(`rm`, ['-rf', '.git/'], { cwd: directory, })
  // return isWin ? shellHelper.execa(`rd`, ['/q', '/s', '.git'], { cwd: directory }) : shellHelper.execa(`rm`, ['-rf', '.git/'], { cwd: directory, })
  return isWin ? shellHelper.execa(`cli`, ['del', `.git`], { cwd: directory }) : shellHelper.execa(`rm`, ['-rf', '.git/'], { cwd: directory, })
}

const vscodeOpen = async (directory) => {
  return shellHelper.execa(`code`, ['.'], { cwd: directory })
}

const tplReplace = (setting) => {
  if (!setting || !setting.isTplSupport) return Promise.resolve(true)
  return new Promise((resolve, reject) => {
    const fsHelper = new FsHelper(path.format({
      dir: process.cwd(),
      name: setting.projectName
    }))

    // fsHelper.copyTplSameDirectory('package1.json', 'package2.json', setting)
    fsHelper.resetTpl('package.json', setting)
    fsHelper.resetTpl('test/index.test.js', setting)
    fsHelper.resetTpl('README.md', setting)
    fsHelper.resetTpl('README.en.md', setting)

    fsHelper.commit(() => resolve(true))
  })
}

const inquirerGitClone = async (dirname, template) => {
  const promptList = [{
    type: 'rawlist',
    message: '请选择一种模版:',
    name: 'template',
    choices: Object.keys(kits)
  }];

  if (!template) {
    let result = await inquirer.prompt(promptList)
    template = result.template
  }

  let setting = await initSetting(template)

  const url = kits[template]
  const projectName = dirname || path.parse(url).name
  const directory = path.format({
    dir: process.cwd(),
    name: projectName
  });

  setting = { projectName, ...setting };
  console.info(setting);

  // (spinner.start(`模版定制中`) && await sleep(2000)) && spinner.succeed(`模版定制完成`);

  try {
    (spinner.start(`模版下载中`) && await gitClone(url, directory)).exitCode === 0 && spinner.succeed(`下载完成`);
    (spinner.start(`模版定制中`) && await tplReplace(setting)) && spinner.succeed(`模版定制完成`);
    (spinner.start(`依赖安装中`) && await install(directory)).exitCode === 0 && spinner.succeed(`依赖安装完成`);
    (spinner.start(`git清理中`) && await clearGit(directory)).exitCode === 0 && spinner.succeed(`git清理完成`);
    (spinner.start(`vscode启动中`) && await vscodeOpen(directory)).exitCode === 0 && spinner.succeed(`vscode启动完成`);
    console.log(`\n${chalk.green('成功!')} 项目准备完毕`)
    console.log(`\ncd ${projectName} && yarn start\n`)
  } catch (error) {
    spinner.fail();
    console.log('😫', error);
  }
}

module.exports = {
  inquirerGitClone,
}